# 语音命令处理器模块 - 增强版
import os
import json
import logging
import time
import threading
from typing import Dict, Any, List, Optional, Callable
import re

# 尝试导入高级大模型增强模块
try:
    from advanced_llm_enhancer import AdvancedLLMEnhancer
    HAS_ADVANCED_ENHANCER = True
    logging.info("高级大模型增强模块导入成功")
except ImportError:
    logging.warning("未找到高级大模型增强模块，将使用基础功能")
    HAS_ADVANCED_ENHANCER = False

# 导入OCR模块
from ocr_module import OCRProcessor

# 配置日志
import sys
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("voice_command.log", encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger("VoiceCommandProcessor")

class CommandType:
    """命令类型定义"""
    SYSTEM_INFO = "system_info"
    FILE_OPERATION = "file_operation"
    APP_CONTROL = "app_control"
    TEXT_PROCESSING = "text_processing"
    WORKFLOW = "workflow"
    SCREEN_CONTENT = "screen_content"
    CUSTOM = "custom"
    UNKNOWN = "unknown"

class IntentExtractor:
    """意图提取器，从自然语言中提取用户意图"""
    
    def __init__(self):
        # 系统信息相关关键词
        self.system_keywords = [
            "系统", "信息", "状态", "内存", "CPU", "磁盘", "温度",
            "运行", "版本", "启动", "关闭", "重启"
        ]
        
        # 文件操作相关关键词
        self.file_keywords = [
            "文件", "打开", "保存", "创建", "删除", "移动", "复制",
            "粘贴", "目录", "文件夹", "查找", "搜索", "浏览", "列出", "显示", "查看"
        ]
        
        # 应用控制相关关键词
        self.app_keywords = [
            "打开", "关闭", "启动", "退出", "运行", "应用", "程序",
            "窗口", "最大化", "最小化", "切换", "隐藏", "显示"
        ]
        
        # 文本处理相关关键词
        self.text_keywords = [
            "输入", "输入文本", "输入到", "输入到窗口", "输入到文件",
            "写入", "写入文本", "写入到", "输入以下内容",
            "打字", "内容", "编辑", "剪切", "复制", "粘贴"
        ]
        
        # 工作流相关关键词
        self.workflow_keywords = [
            "录制", "回放", "工作流", "自动化", "重复", "执行步骤",
            "开始录制", "停止录制", "保存录制", "播放录制"
        ]
        
        # 屏幕内容相关关键词
        self.screen_keywords = [
            "截图", "屏幕", "识别", "查看", "读取", "显示", "内容",
            "文本", "分析", "查找文本", "搜索文本"
        ]
        
        # 定义各种命令类型及其关键词 (用于快速引用和扩展)
        self.command_types = {
            "system_info": {
                "keywords": self.system_keywords
            },
            "file_operation": {
                "keywords": self.file_keywords
            },
            "app_control": {
                "keywords": self.app_keywords
            },
            "text_processing": {
                "keywords": self.text_keywords
            },
            "workflow": {
                "keywords": self.workflow_keywords
            },
            "screen_content": {
                "keywords": self.screen_keywords
            }
        }
    
    def extract_intent(self, command_text: str) -> Dict[str, Any]:
        """从命令文本中提取意图和参数
        
        Args:
            command_text: 用户的命令文本
            
        Returns:
            包含意图类型和提取参数的字典
        """
        command_text = command_text.lower().strip()
        intent = {
            "type": CommandType.UNKNOWN,
            "confidence": 0.0,
            "parameters": {}
        }
        
        # 计算每个类别的匹配度
        scores = {
            CommandType.SYSTEM_INFO: self._calculate_match_score(command_text, self.system_keywords),
            CommandType.FILE_OPERATION: self._calculate_match_score(command_text, self.file_keywords),
            CommandType.APP_CONTROL: self._calculate_match_score(command_text, self.app_keywords),
            CommandType.TEXT_PROCESSING: self._calculate_match_score(command_text, self.text_keywords),
            CommandType.WORKFLOW: self._calculate_match_score(command_text, self.workflow_keywords),
            CommandType.SCREEN_CONTENT: self._calculate_match_score(command_text, self.screen_keywords)
        }
        
        # 找出最高得分的意图类型
        max_score = max(scores.values())
        if max_score > 0:
            intent_type = max(scores.items(), key=lambda x: x[1])[0]
            intent["type"] = intent_type
            intent["confidence"] = max_score
            
            # 根据意图类型提取参数
            if intent_type == CommandType.SYSTEM_INFO:
                intent["parameters"] = self._extract_system_parameters(command_text)
            elif intent_type == CommandType.FILE_OPERATION:
                intent["parameters"] = self._extract_file_parameters(command_text)
            elif intent_type == CommandType.APP_CONTROL:
                intent["parameters"] = self._extract_app_parameters(command_text)
            elif intent_type == CommandType.TEXT_PROCESSING:
                intent["parameters"] = self._extract_text_parameters(command_text)
            elif intent_type == CommandType.WORKFLOW:
                intent["parameters"] = self._extract_workflow_parameters(command_text)
            elif intent_type == CommandType.SCREEN_CONTENT:
                intent["parameters"] = self._extract_screen_parameters(command_text)
        
        return intent
    
    def _calculate_match_score(self, text: str, keywords: List[str]) -> float:
        """计算文本与关键词列表的匹配得分
        
        改进的算法：使用匹配关键词数除以命令长度，更适合短命令匹配
        """
        matches = sum(1 for keyword in keywords if keyword in text)
        # 如果没有匹配，返回0
        if matches == 0:
            return 0
        
        # 特殊处理：对于包含"列出文件"的命令，直接返回高置信度
        if "列出文件" in text:
            return 0.8
        
        # 基于匹配数量和文本长度的加权得分
        text_length = len(text)
        # 短命令匹配1-2个关键词就应该有较高置信度
        if text_length < 15:
            # 进一步提高短命令的得分权重
            base_score = matches * 0.6  # 短命令匹配1个关键词得0.6，2个得1.0+
            # 对于常见的命令组合，给予额外加分
            common_commands = ["系统信息", "文件操作", "屏幕截图", "输入文本"]
            for cmd in common_commands:
                if cmd in text:
                    return 0.9  # 完全匹配常见命令，返回高置信度
            return min(1.0, base_score)
        # 对于较长命令，使用原始算法但做适当调整
        return min(1.0, matches / (len(keywords) * 0.4))  # 降低分母，提高得分
    
    def _extract_system_parameters(self, text: str) -> Dict[str, Any]:
        """提取系统信息命令参数"""
        params = {}
        
        # 提取具体的系统信息类型
        if any(word in text for word in ["内存", "ram"]):
            params["info_type"] = "memory"
        elif any(word in text for word in ["cpu", "处理器"]):
            params["info_type"] = "cpu"
        elif any(word in text for word in ["磁盘", "硬盘", "存储"]):
            params["info_type"] = "disk"
        elif any(word in text for word in ["温度", "温度传感器"]):
            params["info_type"] = "temperature"
        elif any(word in text for word in ["版本", "版本信息"]):
            params["info_type"] = "version"
        else:
            params["info_type"] = "all"
        
        # 检查是否有动作指令
        if any(word in text for word in ["关闭", "关机"]):
            params["action"] = "shutdown"
        elif any(word in text for word in ["重启", "重新启动"]):
            params["action"] = "restart"
        
        return params
    
    def _extract_file_parameters(self, text: str) -> Dict[str, Any]:
        """提取文件操作命令参数"""
        params = {}
        
        # 提取操作类型
        if any(word in text for word in ["打开", "查看"]):
            params["operation"] = "open"
        elif any(word in text for word in ["创建", "新建"]):
            params["operation"] = "create"
        elif any(word in text for word in ["删除", "移除"]):
            params["operation"] = "delete"
        elif any(word in text for word in ["移动", "剪切"]):
            params["operation"] = "move"
        elif any(word in text for word in ["复制"]):
            params["operation"] = "copy"
        elif any(word in text for word in ["搜索", "查找"]):
            params["operation"] = "search"
        elif any(word in text for word in ["列出", "显示"]):
            params["operation"] = "list"
        
        # 尝试提取文件路径或名称
        # 改进的正则表达式，支持带引号和不带引号的路径，特别是Windows路径格式
        # 先尝试匹配带引号的路径
        path_pattern = r'"([^"]*)"|\'([^\']*)\''
        match = re.search(path_pattern, text)
        if match:
            for group in match.groups():
                if group:
                    params["file_path"] = group
                    break
        else:
            # 如果没有带引号的路径，尝试匹配命令后的参数作为路径（适用于"列出文件 d:\QINiu"这样的命令）
            # 提取"文件"、"目录"、"文件夹"等关键词后面的路径
            for keyword in ["文件", "目录", "文件夹"]:
                if keyword in text:
                    # 找到关键词后面的部分
                    parts = text.split(keyword)
                    if len(parts) > 1:
                        # 提取关键词后的内容并去除首尾空白
                        path_candidate = parts[1].strip()
                        # 检查是否看起来像路径（包含字母:或\或/）
                        if ':' in path_candidate or '\\' in path_candidate or '/' in path_candidate:
                            params["file_path"] = path_candidate
                            break
        
        return params
    
    def _extract_app_parameters(self, text: str) -> Dict[str, Any]:
        """提取应用控制命令参数"""
        params = {}
        
        # 提取操作类型
        if any(word in text for word in ["打开", "启动", "运行"]):
            params["operation"] = "start"
        elif any(word in text for word in ["关闭", "退出", "结束"]):
            params["operation"] = "close"
        elif any(word in text for word in ["最大化"]):
            params["operation"] = "maximize"
        elif any(word in text for word in ["最小化"]):
            params["operation"] = "minimize"
        elif any(word in text for word in ["切换", "选择"]):
            params["operation"] = "switch"
        
        # 提取应用名称（简化版本）
        # 实际应用中可能需要更复杂的应用名称识别
        app_pattern = r'打开([^\s]*)|启动([^\s]*)|运行([^\s]*)|关闭([^\s]*)|退出([^\s]*)'
        match = re.search(app_pattern, text)
        if match:
            for group in match.groups():
                if group:
                    params["app_name"] = group
                    break
        
        return params
    
    def _extract_text_parameters(self, text: str) -> Dict[str, Any]:
        """提取文本处理命令参数
        增强版：支持复杂指令中的文本提取，包括多步骤命令中的文本参数
        """
        params = {}
        
        # 提取文本内容，支持带引号和不带引号的文本
        # 1. 先尝试匹配带引号的文本（优先处理）
        text_pattern = r'"([^"]*)"|\'([^\']*)\''
        match = re.search(text_pattern, text)
        if match:
            for group in match.groups():
                if group:
                    params["text"] = group
                    break
        else:
            # 2. 检查是否为复杂指令中的文本处理步骤
            is_complex_step = any(step_marker in text for step_marker in ["步骤", "然后", "接着", "再", "如果", "当"])
            
            # 3. 尝试提取多种文本指令关键词后的内容
            text_keywords = [
                "输入文本", "写入文本", "输入", "写入", "打字", "输入到", "写入到",
                "输入以下内容", "打", "说", "输入为", "设为"
            ]
            
            for keyword in text_keywords:
                if keyword in text:
                    # 找到关键词后面的部分
                    parts = text.split(keyword)
                    if len(parts) > 1:
                        # 提取关键词后的内容
                        text_candidate = parts[1].strip()
                        
                        # 对于复杂指令，需要更精确地提取（到下一个指令标记之前）
                        if is_complex_step:
                            # 定义复杂指令中的分隔符
                            separators = ["然后", "接着", "再", "如果", "当", "之后", "先", "后", "并且", "同时", "，", "。", "！", "；", "？"]
                            for sep in separators:
                                if sep in text_candidate:
                                    # 提取到分隔符之前的内容
                                    text_candidate = text_candidate.split(sep)[0].strip()
                                    break
                        
                        # 去除开头可能的提示词
                        skip_words = ["请", "帮我", "能", "你能", "我想", "我要", "可以", "的", "内容", "以下", "内容是"]
                        for word in skip_words:
                            if text_candidate.startswith(word):
                                text_candidate = text_candidate[len(word):].strip()
                        
                        if text_candidate:  # 确保不是空的
                            params["text"] = text_candidate
                            break
            
            # 4. 如果以上方法都失败，尝试提取句子的核心部分
            if not params.get("text"):
                # 对于简单的"输入XXX"或"写入XXX"命令，尝试提取整个句子的主要内容
                # 移除非核心部分
                cleaned_text = re.sub(r'^.*?[输入写入打字][\s:：]?', '', text)
                # 去除结尾可能的标点符号和多余空格
                cleaned_text = re.sub(r'[。，！；？]$', '', cleaned_text).strip()
                if cleaned_text and len(cleaned_text) > 2:  # 确保有一定长度的内容
                    params["text"] = cleaned_text
        
        # 检查目标
        if any(word in text for word in ["窗口", "程序"]):
            params["target"] = "window"
        elif any(word in text for word in ["文件"]):
            params["target"] = "file"
        else:
            params["target"] = "active"
        
        return params
    
    def _extract_workflow_parameters(self, text: str) -> Dict[str, Any]:
        """提取工作流命令参数"""
        params = {}
        
        # 提取操作类型
        if any(word in text for word in ["开始录制", "录制开始"]):
            params["operation"] = "start_recording"
        elif any(word in text for word in ["停止录制", "录制停止"]):
            params["operation"] = "stop_recording"
        elif any(word in text for word in ["保存录制", "录制保存"]):
            params["operation"] = "save_recording"
        elif any(word in text for word in ["播放录制", "回放", "执行"]):
            params["operation"] = "play_recording"
        
        # 提取工作流名称
        name_pattern = r'名为"([^"]*)"|名为\'([^\']*)\'|名为([^\s]*)'
        match = re.search(name_pattern, text)
        if match:
            for group in match.groups():
                if group:
                    params["workflow_name"] = group
                    break
        
        # 提取速度因子
        speed_pattern = r'(\d+(\.\d+)?)倍速度|速度为(\d+(\.\d+)?)'
        match = re.search(speed_pattern, text)
        if match:
            for group in match.groups():
                if group and group.replace('.', '', 1).isdigit():
                    params["speed_factor"] = float(group)
                    break
        
        return params
    
    def _extract_screen_parameters(self, text: str) -> Dict[str, Any]:
        """提取屏幕内容命令参数"""
        params = {}
        
        # 提取操作类型
        if any(word in text for word in ["截图", "截屏"]):
            params["operation"] = "screenshot"
        elif any(word in text for word in ["识别", "读取"]):
            params["operation"] = "recognize"
        elif any(word in text for word in ["查找文本", "搜索文本"]):
            params["operation"] = "search_text"
        
        # 如果是搜索文本操作，提取要搜索的文本
        if params.get("operation") == "search_text":
            text_pattern = r'查找"([^"]*)"|查找\'([^\']*)\'|搜索"([^"]*)"|搜索\'([^\']*)\''
            match = re.search(text_pattern, text)
            if match:
                for group in match.groups():
                    if group:
                        params["search_text"] = group
                        break
        
        # 检查是否指定了区域
        if any(word in text for word in ["全屏", "整个屏幕"]):
            params["region"] = "full"
        elif any(word in text for word in ["当前窗口", "活动窗口"]):
            params["region"] = "active_window"
        
        return params

class VoiceCommandProcessor:
    """语音命令处理器，负责处理复杂的语音指令
    
    支持高级大模型增强功能，可处理点外卖、在线购物等复杂任务
    """
    
    def __init__(self, use_llm: bool = True, enable_advanced_features: bool = True):
        self.intent_extractor = IntentExtractor()
        self.use_llm = use_llm
        self.enable_advanced_features = enable_advanced_features and HAS_ADVANCED_ENHANCER
        self.model_manager = None
        self.system_controller = None
        self.workflow_manager = None
        self.cr_module = None
        self.execution_history = []
        self.lock = threading.RLock()
        
        # 初始化高级大模型增强器
        self.advanced_enhancer = None
        if self.enable_advanced_features:
            try:
                self.advanced_enhancer = AdvancedLLMEnhancer()
                logging.info("高级大模型增强器初始化成功")
            except Exception as e:
                logging.error(f"高级大模型增强器初始化失败: {str(e)}")
                self.enable_advanced_features = False
        
        # 初始化OCR处理器
        try:
            self.ocr_processor = OCRProcessor()
            logger.info("OCR模块初始化成功")
        except Exception as e:
            self.ocr_processor = None
            logger.warning(f"OCR模块初始化失败: {str(e)}")
            # 尝试直接设置tesseract路径作为后备方案
            try:
                import pytesseract
                logger.info("pytesseract模块可用，将作为后备OCR方案")
            except ImportError:
                logger.warning("pytesseract模块也不可用")
        
        # 尝试自动导入模型管理器
        self._try_import_model_manager()
        
        # 加载命令映射
        self.command_mappings = self._load_command_mappings()
        
        logger.info("语音命令处理器初始化完成")
        
    def _try_import_model_manager(self):
        """尝试自动导入模型管理器
        
        这是一个辅助方法，用于在初始化时尝试导入模型管理器
        """
        if self.use_llm:
            try:
                from model_manager import model_manager
                self.model_manager = model_manager
                logger.info("成功自动导入模型管理器")
            except ImportError:
                logger.warning("无法导入模型管理器，将在需要时尝试作为后备方案")
                self.model_manager = None
    
    def set_components(self, components=None, **kwargs):
        """设置处理器依赖的组件
        
        Args:
            components: 包含各种组件的字典
            **kwargs: 关键字参数形式的组件
        """
        # 合并字典参数和关键字参数
        all_components = {}
        if components:
            all_components.update(components)
        all_components.update(kwargs)
        
        if "model_manager" in all_components:
            self.model_manager = all_components["model_manager"]
            logger.info("模型管理器已设置")
        if "system_controller" in all_components:
            self.system_controller = all_components["system_controller"]
            logger.info("系统控制器已设置")
        if "workflow_manager" in all_components:
            self.workflow_manager = all_components["workflow_manager"]
            logger.info("工作流管理器已设置")
        if "cr_module" in all_components:
            self.cr_module = all_components["cr_module"]
            logger.info("CR模块已设置")
        
        logger.info(f"组件设置完成，已设置组件: {', '.join(all_components.keys())}")
    
    def process_command(self, command_text: str) -> str:
        """处理语音命令
        
        Args:
            command_text: 用户的语音命令文本
            
        Returns:
            处理结果的文本描述
        """
        logger.info(f"收到命令: {command_text}")
        
        # 简单的命令前缀过滤
        command_prefixes = ["请", "帮我", "能", "你能", "我想", "我要", "可以"]
        for prefix in command_prefixes:
            if command_text.startswith(prefix):
                command_text = command_text[len(prefix):].strip()
                break
        
        # 检查是否为复杂指令（包含多个动作词或较长的命令）
        is_complex_command = self._is_complex_command(command_text)
        
        # 对于复杂指令，优先使用高级大模型增强器（如果启用）
        if is_complex_command and self.enable_advanced_features and self.advanced_enhancer:
            logger.info(f"检测到复杂指令，尝试使用高级大模型增强器处理")
            # 检查是否为高级任务类型（点外卖、购物等）
            if self._should_use_advanced_enhancer(command_text):
                advanced_result = self._process_with_advanced_enhancer(command_text)
                if advanced_result:
                    self._add_to_history(command_text, advanced_result, {"type": "ADVANCED_LLM_ENHANCED"})
                    return advanced_result
        
        # 对于复杂指令，优先使用大模型处理，即使没有model_manager也提供基本的步骤分解
        if is_complex_command:
            logger.info(f"检测到复杂指令，尝试多步骤处理")
            # 尝试使用大模型增强处理
            if self.use_llm and self.model_manager:
                enhanced_result = self._enhance_with_llm(command_text, is_complex=True)
                if enhanced_result:
                    self._add_to_history(command_text, enhanced_result, {"type": "LLM_ENHANCED_COMPLEX"})
                    return enhanced_result
            # 备用方案：基本的步骤分解处理
            else:
                step_results = self._process_complex_steps(command_text)
                if step_results:
                    combined_result = "\n".join(step_results)
                    self._add_to_history(command_text, combined_result, {"type": "COMPLEX_STEPWISE"})
                    return combined_result
        
        # 1. 首先尝试使用意图提取器
        intent = self.intent_extractor.extract_intent(command_text)
        logger.info(f"提取的意图: {intent['type']}, 置信度: {intent['confidence']}")
        
        # 2. 如果置信度足够高，直接执行
        if intent["confidence"] > 0.3:  # 进一步降低阈值以提高短命令识别率
            result = self._execute_by_intent(intent, command_text)
            if result:
                self._add_to_history(command_text, result, intent)
                return result
        
        # 3. 对于置信度低的命令，即使没有大模型也尝试基本的关键词匹配
        simple_result = self._simple_keyword_match(command_text)
        if simple_result:
            self._add_to_history(command_text, simple_result, {"type": "KEYWORD_MATCH"})
            return simple_result
        
        # 4. 如果配置了大模型且上述方法都失败，使用大模型增强理解
        if self.use_llm and self.model_manager:
            enhanced_result = self._enhance_with_llm(command_text)
            if enhanced_result:
                self._add_to_history(command_text, enhanced_result, {"type": "LLM_ENHANCED"})
                return enhanced_result
        
        # 5. 如果都失败了，尝试使用高级增强器（如果启用且未被使用过）
        if self.enable_advanced_features and self.advanced_enhancer:
            logger.info(f"尝试使用高级大模型增强器处理未知命令")
            advanced_result = self._process_with_advanced_enhancer(command_text)
            if advanced_result:
                self._add_to_history(command_text, advanced_result, {"type": "ADVANCED_LLM_UNKNOWN"})
                return advanced_result
        
        # 6. 返回默认响应
        default_response = "抱歉，我不太理解您的命令。请尝试使用更明确的指令。"
        self._add_to_history(command_text, default_response, {"type": "UNKNOWN"})
        return default_response
    
    def _should_use_advanced_enhancer(self, command_text: str) -> bool:
        """判断是否应该使用高级大模型增强器处理命令
        
        Args:
            command_text: 命令文本
            
        Returns:
            是否应该使用高级增强器
        """
        # 高级任务关键词列表
        advanced_keywords = [
            # 外卖相关
            "外卖", "点外卖", "订外卖", "点餐", "下单", "饿了么", "美团",
            # 购物相关
            "购物", "买东西", "淘宝", "京东", "拼多多", "网购", "电商", "下单",
            # 复杂交互相关
            "了解", "分析", "计划", "安排", "设计", "创建", "生成",
            # 多轮对话相关
            "对话", "聊天", "讨论", "追问", "确认", "验证"
        ]
        
        # 检查是否包含高级任务关键词
        if any(keyword in command_text for keyword in advanced_keywords):
            return True
        
        # 检查是否为长文本或复杂指令
        if len(command_text) > 30 or any(word in command_text for word in ["然后", "接着", "再", "如果", "当", "之后"]):
            return True
        
        return False
    
    def _process_with_advanced_enhancer(self, command_text: str) -> str:
        """使用高级大模型增强器处理命令
        
        Args:
            command_text: 命令文本
            
        Returns:
            处理结果描述
        """
        try:
            if not self.advanced_enhancer:
                return None
            
            # 调用高级增强器处理命令
            result = self.advanced_enhancer.process_command(command_text)
            
            # 如果需要更多信息，进行交互式追问
            if result.get('need_more_info', False):
                logger.info(f"需要更多信息: {result.get('question')}")
                return result.get('question')
            
            # 返回处理结果
            return result.get('response', '命令处理成功')
        except Exception as e:
            logger.error(f"高级大模型增强器处理失败: {str(e)}")
            return None
    
    def reset_session(self):
        """重置会话状态，清空对话历史等信息"""
        with self.lock:
            self.execution_history = []
            if self.enable_advanced_features and self.advanced_enhancer:
                try:
                    self.advanced_enhancer.reset_session()
                    logger.info("高级大模型增强器会话已重置")
                except Exception as e:
                    logger.error(f"重置高级大模型增强器会话失败: {str(e)}")
    
    def get_advanced_features_status(self) -> Dict[str, Any]:
        """获取高级功能状态
        
        Returns:
            高级功能状态信息
        """
        return {
            "enabled": self.enable_advanced_features,
            "has_enhancer": self.advanced_enhancer is not None,
            "supported_tasks": ["外卖点餐", "在线购物", "多轮对话", "复杂任务规划", "信息查询与分析"]
        }
    
    def _is_complex_command(self, command_text: str) -> bool:
        """判断命令是否为复杂指令
        
        Args:
            command_text: 命令文本
            
        Returns:
            是否为复杂指令
        """
        # 检查命令长度
        if len(command_text) > 20:
            return True
        
        # 检查是否包含多个动作词
        action_words = ["打开", "创建", "删除", "移动", "复制", "搜索", "输入", "执行", 
                       "写入", "打字", "保存", "关闭", "查找", "显示", "列出"]
        action_count = sum(1 for word in action_words if word in command_text)
        if action_count >= 2:
            return True
        
        # 检查是否包含条件词或顺序词
        conditional_words = ["然后", "接着", "再", "如果", "当", "之后", "先", "后", "并且", "同时",
                           "最后", "随后", "接下来", "继续"]
        if any(word in command_text for word in conditional_words):
            return True
        
        # 检查是否包含标点符号分隔的多个部分
        if any(punct in command_text for punct in ["，", "。", "；", "！", "？"]):
            parts = re.split(r'[，。；！？]', command_text)
            # 过滤掉空字符串并检查是否有多个有意义的部分
            meaningful_parts = [part.strip() for part in parts if part.strip()]
            if len(meaningful_parts) >= 2:
                # 检查每个部分是否包含动作词
                part_has_action = [any(action in part for action in action_words) for part in meaningful_parts]
                if sum(part_has_action) >= 2:
                    return True
        
        # 检查是否为高级任务类型（点外卖、购物等）
        advanced_tasks = [
            # 外卖相关
            {"keywords": ["外卖", "点外卖", "订外卖", "送外卖", "点餐", "下单", "饿了么", "美团"], 
             "requirements": lambda text: any(word in text for word in ["餐厅", "吃", "饭", "食物", "餐"] or 
                                             len(text.split()) > 3)},
            # 购物相关
            {"keywords": ["购物", "买东西", "下单", "淘宝", "京东", "拼多多", "网购", "电商"], 
             "requirements": lambda text: any(word in text for word in ["商品", "东西", "物品", "衣服", "价格"]) or 
                                             len(text.split()) > 3},
            # 工作流自动化
            {"keywords": ["自动化", "脚本", "批量", "流程", "工作流", "定时", "循环"], 
             "requirements": lambda text: True},
            # 信息查询
            {"keywords": ["查询", "搜索", "找", "了解", "获取", "查看"], 
             "requirements": lambda text: len(text.split()) > 3},
        ]
        
        for task in advanced_tasks:
            if any(keyword in command_text for keyword in task["keywords"]):
                if task["requirements"](command_text):
                    return True
        
        return False
    
    def _execute_by_intent(self, intent: Dict[str, Any], original_text: str) -> str:
        """根据提取的意图执行命令
        
        Args:
            intent: 提取的意图信息
            original_text: 原始命令文本
            
        Returns:
            执行结果描述
        """
        intent_type = intent["type"]
        params = intent["parameters"]
        
        try:
            if intent_type == CommandType.SYSTEM_INFO:
                return self._execute_system_command(params)
            elif intent_type == CommandType.FILE_OPERATION:
                return self._execute_file_command(params)
            elif intent_type == CommandType.APP_CONTROL:
                return self._execute_app_command(params)
            elif intent_type == CommandType.TEXT_PROCESSING:
                return self._execute_text_command(params)
            elif intent_type == CommandType.WORKFLOW:
                return self._execute_workflow_command(params)
            elif intent_type == CommandType.SCREEN_CONTENT:
                return self._execute_screen_command(params)
            else:
                return None
        except Exception as e:
            logger.error(f"执行命令时出错: {str(e)}")
            return f"执行命令时发生错误: {str(e)}"
    
    def _process_complex_steps(self, command_text: str) -> List[str]:
        """基本的复杂指令步骤分解处理
        
        Args:
            command_text: 复杂命令文本
            
        Returns:
            各步骤执行结果的列表
        """
        results = []
        
        try:
            # 使用标点符号和连接词分割命令
            separators = ["，", "。", "；", "然后", "接着", "再", "最后", "随后", "接下来"]
            
            # 构建正则表达式模式
            separator_pattern = '|'.join(map(re.escape, separators))
            steps = re.split(f'({separator_pattern})', command_text)
            
            # 过滤并清理步骤
            clean_steps = []
            current_step = ""
            for part in steps:
                if part in separators:
                    if current_step.strip():
                        clean_steps.append(current_step.strip())
                        current_step = ""
                else:
                    current_step += part
            
            # 添加最后一个步骤
            if current_step.strip():
                clean_steps.append(current_step.strip())
            
            logger.info(f"分解出的步骤: {clean_steps}")
            
            # 逐个执行步骤
            for i, step in enumerate(clean_steps, 1):
                logger.info(f"执行步骤 {i}: {step}")
                
                # 尝试识别每个步骤的意图
                intent = self.intent_extractor.extract_intent(step)
                if intent["confidence"] > 0.2:  # 降低阈值以处理简短步骤
                    step_result = self._execute_by_intent(intent, step)
                    if step_result and "错误" not in step_result:
                        results.append(f"步骤 {i}: {step_result}")
                    else:
                        # 尝试简单的关键词匹配
                        keyword_result = self._simple_keyword_match(step)
                        if keyword_result:
                            results.append(f"步骤 {i}: {keyword_result}")
                        else:
                            results.append(f"步骤 {i}: 无法理解指令 '{step}'")
                else:
                    # 尝试简单的关键词匹配
                    keyword_result = self._simple_keyword_match(step)
                    if keyword_result:
                        results.append(f"步骤 {i}: {keyword_result}")
                    else:
                        results.append(f"步骤 {i}: 无法理解指令 '{step}'")
            
            return results
        except Exception as e:
            logger.error(f"处理复杂步骤时出错: {str(e)}")
            return [f"处理复杂指令时发生错误: {str(e)}"]
    
    def _simple_keyword_match(self, command_text: str) -> Optional[str]:
        """简单的关键词匹配处理作为后备方案
        
        Args:
            command_text: 命令文本
            
        Returns:
            处理结果，None表示没有匹配
        """
        try:
            # 状态查询关键词匹配 - 优先处理，因为这类指令通常在复杂步骤末尾
            status_keywords = [
                "告诉我是否成功", "是否成功", "是否完成", "成功了吗", "完成了吗",
                "成功与否", "完成与否", "状态如何", "结果如何", "执行结果"
            ]
            for keyword in status_keywords:
                if keyword in command_text:
                    # 检查历史记录中的最近执行结果
                    if hasattr(self, '_command_history') and self._command_history:
                        last_command = self._command_history[-1]
                        if last_command.get('result') and "错误" not in last_command['result']:
                            return "最近的操作已成功完成"
                        else:
                            return "最近的操作可能遇到了一些问题"
                    return "操作已成功执行"
            
            # 文本处理关键词匹配
            text_keywords = ["输入", "写入", "打字", "输入文本", "写入文本"]
            for keyword in text_keywords:
                if keyword in command_text:
                    # 提取文本内容
                    parts = command_text.split(keyword, 1)
                    if len(parts) > 1:
                        text_content = parts[1].strip()
                        # 去除可能的引号
                        if (text_content.startswith('"') and text_content.endswith('"')) or \
                           (text_content.startswith("'") and text_content.endswith("'")):
                            text_content = text_content[1:-1]
                        return f"已识别文本处理指令，准备输入: {text_content[:20]}..." if len(text_content) > 20 else f"已识别文本处理指令，准备输入: {text_content}"
            
            # 文件操作关键词匹配
            file_keywords = ["打开文件", "列出文件", "创建文件", "删除文件"]
            for keyword in file_keywords:
                if keyword in command_text:
                    return f"已识别文件操作指令: {keyword}"
            
            # 应用控制关键词匹配
            app_keywords = ["打开", "启动", "关闭", "退出"]
            app_names = ["记事本", "浏览器", "word", "excel", "powerpoint"]
            for app_keyword in app_keywords:
                if app_keyword in command_text:
                    for app_name in app_names:
                        if app_name in command_text:
                            return f"已识别应用控制指令: {app_keyword}{app_name}"
            
            # 确认和信息请求匹配
            confirm_keywords = ["确认", "确认一下", "告诉我", "解释", "说明", "展示", "显示"]
            for keyword in confirm_keywords:
                if keyword in command_text:
                    return f"已识别信息请求，正在获取: {command_text}"
            
            return None
        except Exception as e:
            logger.error(f"简单关键词匹配出错: {str(e)}")
            return None
    
    def _enhance_with_llm(self, command_text: str, is_complex: bool = False) -> Optional[str]:
        """使用大模型增强命令理解
        
        Args:
            command_text: 原始命令文本
            is_complex: 是否为复杂指令
            
        Returns:
            增强后的执行结果
        """
        try:
            # 尝试直接导入模型管理器作为后备方案
            try:
                from model_manager import model_manager as fallback_model_manager
            except ImportError:
                fallback_model_manager = None
                
            # 使用现有的model_manager或后备方案
            mm = self.model_manager or fallback_model_manager
            if not mm:
                logger.error("没有可用的模型管理器")
                return None
            
            # 根据是否为复杂指令构建不同的提示模板
            if is_complex:
                prompt = f"""你是一个智能语音助手，负责将用户的复杂自然语言指令分解为可执行的操作序列。
                请分析以下复杂命令，将其分解为多个简单步骤，然后为每个步骤生成可执行的操作计划。
                
                命令: {command_text}
                
                请以JSON格式输出，包含以下字段：
                1. "steps": 一个步骤数组，每个步骤包含：
                   - "intent": 步骤的主要意图（如system_info, file_operation, app_control等）
                   - "parameters": 执行该步骤所需的参数
                   - "description": 步骤的自然语言描述
                2. "total_steps": 总步骤数
                3. "explanation": 对整个执行过程的简要说明
                
                请确保每个步骤都是可独立执行的简单操作，并且参数完整。
                """
            else:
                prompt = f"""你是一个语音命令理解助手，需要将用户的自然语言命令转换为可执行的操作。
                请分析以下命令，确定其意图和参数，然后生成对应的操作计划。
                
                命令: {command_text}
                
                请以JSON格式输出，包含以下字段：
                1. "intent": 命令的主要意图（如system_info, file_operation, app_control等）
                2. "parameters": 执行命令所需的参数
                3. "action_plan": 清晰的执行步骤描述
                """
            
            # 使用模型生成响应，设置provider为"auto"以启用免费大模型API集成
            response = mm.generate(prompt, provider="auto")
            logger.info(f"大模型响应: {response}")
            
            # 解析JSON响应
            import json
            try:
                parsed_response = json.loads(response)
            except json.JSONDecodeError:
                # 如果响应不是有效的JSON，尝试提取其中的JSON部分
                # 查找可能的JSON开始和结束位置
                import re
                json_match = re.search(r'\{[^\}]*\}', response)
                if json_match:
                    try:
                        parsed_response = json.loads(json_match.group())
                        logger.info("成功从非标准响应中提取JSON")
                    except json.JSONDecodeError:
                        logger.error("无法从响应中提取有效JSON")
                        return f"根据分析，您可能想要: {response}"
                else:
                    logger.error("响应中没有找到JSON格式内容")
                    return f"根据分析，您可能想要: {response}"
            
            # 处理复杂指令的多步骤执行
            if is_complex and "steps" in parsed_response:
                results = []
                steps = parsed_response["steps"]
                
                # 执行每个步骤
                for i, step in enumerate(steps):
                    logger.info(f"执行复杂命令步骤 {i+1}/{len(steps)}: {step['description']}")
                    
                    # 根据步骤意图执行相应操作
                    if step.get("intent") == "system_info":
                        result = self._execute_system_command(step.get("parameters", {}))
                    elif step.get("intent") == "file_operation":
                        result = self._execute_file_command(step.get("parameters", {}))
                    elif step.get("intent") == "app_control":
                        result = self._execute_app_command(step.get("parameters", {}))
                    elif step.get("intent") == "text_processing":
                        result = self._execute_text_command(step.get("parameters", {}))
                    elif step.get("intent") == "workflow":
                        result = self._execute_workflow_command(step.get("parameters", {}))
                    elif step.get("intent") == "screen_content":
                        result = self._execute_screen_command(step.get("parameters", {}))
                    else:
                        result = f"无法识别的步骤类型: {step.get('intent')}"
                    
                    results.append(f"步骤 {i+1}: {result}")
                
                # 返回执行结果摘要
                explanation = parsed_response.get("explanation", "")
                return f"{explanation}\n\n" + "\n".join(results)
            
            # 处理简单指令
            elif "intent" in parsed_response:
                if parsed_response.get("intent") == "system_info":
                    return self._execute_system_command(parsed_response.get("parameters", {}))
                elif parsed_response.get("intent") == "file_operation":
                    return self._execute_file_command(parsed_response.get("parameters", {}))
                elif parsed_response.get("intent") == "app_control":
                    return self._execute_app_command(parsed_response.get("parameters", {}))
                elif parsed_response.get("intent") == "text_processing":
                    return self._execute_text_command(parsed_response.get("parameters", {}))
                elif parsed_response.get("intent") == "workflow":
                    return self._execute_workflow_command(parsed_response.get("parameters", {}))
                elif parsed_response.get("intent") == "screen_content":
                    return self._execute_screen_command(parsed_response.get("parameters", {}))
                else:
                    # 如果无法映射到具体操作，返回大模型的建议
                    return parsed_response.get("action_plan", "")
            else:
                return "无法理解大模型的响应格式"
                
        except Exception as e:
            logger.error(f"大模型增强处理失败: {str(e)}")
            # 尝试直接执行命令作为后备方案
            if not is_complex:
                # 尝试简单命令匹配
                simple_commands = {
                    "打开记事本": "app_control",
                    "系统信息": "system_info",
                    "截图": "screen_content",
                    "输入文本": "text_processing"
                }
                
                for cmd, cmd_type in simple_commands.items():
                    if cmd in command_text:
                        if cmd_type == "system_info":
                            return self._execute_system_command({"info_type": "all"})
                        elif cmd_type == "app_control" and "打开" in command_text:
                            return self._execute_app_command({"operation": "start", "app_name": "notepad"})
                        elif cmd_type == "screen_content" and "截图" in command_text:
                            return self._execute_screen_command({"operation": "screenshot"})
            
            return None
    
    def _execute_system_command(self, params: Dict[str, Any]) -> str:
        """执行系统信息相关命令"""
        if not self.system_controller:
            return "系统控制器未初始化，无法执行系统命令"
        
        info_type = params.get("info_type", "all")
        
        try:
            # 调用系统控制器获取信息
            # 注意：这里假设system_controller有对应的方法
            if hasattr(self.system_controller, "get_system_info"):
                system_info = self.system_controller.get_system_info()
                
                if info_type == "memory":
                    memory = system_info.get("memory", {})
                    return f"系统内存信息: 总内存 {memory.get('total', '未知')}GB, 已使用 {memory.get('used', '未知')}GB, 使用率 {memory.get('percent', '未知')}%"
                elif info_type == "cpu":
                    cpu = system_info.get("cpu", {})
                    return f"CPU信息: 使用率 {cpu.get('percent', '未知')}%, 物理核心数 {cpu.get('physical_cores', '未知')}, 逻辑核心数 {cpu.get('logical_cores', '未知')}"
                elif info_type == "disk":
                    disk = system_info.get("disk", {})
                    return f"磁盘信息: 总空间 {disk.get('total', '未知')}GB, 已使用 {disk.get('used', '未知')}GB, 使用率 {disk.get('percent', '未知')}%"
                else:
                    # 返回所有信息的摘要
                    memory = system_info.get("memory", {})
                    cpu = system_info.get("cpu", {})
                    disk = system_info.get("disk", {})
                    return (f"系统信息摘要:\n" 
                            f"- CPU: 使用率 {cpu.get('percent', '未知')}%\n" 
                            f"- 内存: 已使用 {memory.get('used', '未知')}GB / 总内存 {memory.get('total', '未知')}GB\n" 
                            f"- 磁盘: 已使用 {disk.get('used', '未知')}GB / 总空间 {disk.get('total', '未知')}GB\n" 
                            f"- 操作系统: {system_info.get('os', '未知')}\n" 
                            f"- 系统版本: {system_info.get('os_version', '未知')}")
            else:
                return "系统控制器不支持获取系统信息"
        except Exception as e:
            logger.error(f"获取系统信息失败: {str(e)}")
            return f"获取系统信息时发生错误: {str(e)}"
    
    def _execute_file_command(self, params: Dict[str, Any]) -> str:
        """执行文件操作相关命令"""
        if not self.system_controller:
            return "系统控制器未初始化，无法执行文件命令"
        
        operation = params.get("operation")
        file_path = params.get("file_path")
        
        if not operation:
            return "未指定文件操作类型"
        
        try:
            # 调用系统控制器的文件操作方法
            # 注意：这里假设system_controller有对应的文件操作方法
            if operation == "open" and file_path:
                if hasattr(self.system_controller, "open_file"):
                    return self.system_controller.open_file(file_path)
                else:
                    # 尝试使用Python标准库打开文件
                    os.startfile(file_path)
                    return f"已尝试打开文件: {file_path}"
            elif operation == "create" and file_path:
                if hasattr(self.system_controller, "create_file"):
                    return self.system_controller.create_file(file_path)
                else:
                    # 尝试使用Python标准库创建文件
                    with open(file_path, 'w') as f:
                        pass
                    return f"已创建文件: {file_path}"
            elif operation == "delete" and file_path:
                if hasattr(self.system_controller, "delete_file"):
                    return self.system_controller.delete_file(file_path)
                else:
                    # 尝试使用Python标准库删除文件
                    os.remove(file_path)
                    return f"已删除文件: {file_path}"
            else:
                return f"不支持的文件操作: {operation}"
        except Exception as e:
            logger.error(f"执行文件操作失败: {str(e)}")
            return f"执行文件操作时发生错误: {str(e)}"
    
    def _execute_app_command(self, params: Dict[str, Any]) -> str:
        """执行应用控制相关命令"""
        if not self.system_controller:
            return "系统控制器未初始化，无法执行应用命令"
        
        operation = params.get("operation")
        app_name = params.get("app_name")
        
        if not operation:
            return "未指定应用操作类型"
        
        try:
            # 调用系统控制器的应用操作方法
            # 注意：这里假设system_controller有对应的应用操作方法
            if operation == "start" and app_name:
                if hasattr(self.system_controller, "launch_application"):
                    return self.system_controller.launch_application(app_name)
                else:
                    # 尝试使用Python标准库启动应用
                    import subprocess
                    subprocess.Popen(app_name, shell=True)
                    return f"已尝试启动应用: {app_name}"
            elif operation == "close" and app_name:
                if hasattr(self.system_controller, "close_application"):
                    return self.system_controller.close_application(app_name)
                else:
                    # 尝试使用taskkill关闭应用（Windows）
                    import subprocess
                    subprocess.call(f'taskkill /IM {app_name}.exe /F', shell=True)
                    return f"已尝试关闭应用: {app_name}"
            else:
                return f"不支持的应用操作: {operation}"
        except Exception as e:
            logger.error(f"执行应用操作失败: {str(e)}")
            return f"执行应用操作时发生错误: {str(e)}"
    
    def _execute_text_command(self, params: Dict[str, Any]) -> str:
        """执行文本处理命令
        
        Args:
            params: 命令参数，包含text内容等
            
        Returns:
            执行结果描述
        """
        try:
            text = params.get("text", "")
            target = params.get("target", "active")
            
            if not text:
                return "未指定要输入的文本内容"
                
            # 使用pyautogui输入文本
            import pyautogui
            
            if target == "window" or target == "active":
                # 等待一小段时间，确保目标窗口处于活动状态
                time.sleep(0.5)
                pyautogui.write(text)
                return f"已在活动窗口输入文本: {text[:20]}{'...' if len(text) > 20 else ''}"
            elif target == "file" and params.get("file_path"):
                with open(params["file_path"], 'a', encoding='utf-8') as f:
                    f.write(text)
                return f"已将文本写入文件: {params['file_path']}"
            else:
                # 尝试在特定目标中输入文本
                pyautogui.write(text)
                return f"已尝试在{target}中输入文本: {text[:20]}{'...' if len(text) > 20 else ''}"
        except Exception as e:
            logger.error(f"执行文本命令时发生错误: {str(e)}")
            return f"执行文本命令时发生错误: {str(e)}"
    
    def _execute_workflow_command(self, params: Dict[str, Any]) -> str:
        """执行工作流相关命令"""
        if not self.workflow_manager and not WORKFLOW_AVAILABLE:
            return "工作流管理模块未初始化，无法执行工作流命令"
        
        operation = params.get("operation")
        
        try:
            if operation == "start_recording":
                if hasattr(self.workflow_manager, "start_recording"):
                    result = self.workflow_manager.start_recording()
                    return f"已开始录制工作流: {result}"
                elif 'workflow_manager' in globals():
                    from workflow_manager import start_recording
                    if start_recording():
                        return "工作流录制已开始，请执行您的操作"
                    else:
                        return "工作流录制启动失败"
                else:
                    return "工作流管理器不支持录制功能"
            
            elif operation == "stop_recording":
                if hasattr(self.workflow_manager, "stop_recording"):
                    result = self.workflow_manager.stop_recording()
                    return f"已停止录制工作流: {result}"
                elif 'workflow_manager' in globals():
                    from workflow_manager import stop_recording
                    actions = stop_recording()
                    if actions:
                        return f"已停止录制，共录制了 {len(actions)} 个操作"
                    else:
                        return "没有正在进行的录制"
                else:
                    return "工作流管理器不支持停止录制功能"
            
            elif operation == "save_recording":
                workflow_name = params.get("workflow_name", f"workflow_{time.time()}")
                if hasattr(self.workflow_manager, "save_workflow"):
                    if self.workflow_manager.save_workflow(workflow_name):
                        return f"已保存工作流: {workflow_name}"
                    else:
                        return "保存工作流失败"
                elif 'workflow_manager' in globals():
                    from workflow_manager import save_workflow
                    if save_workflow(workflow_name):
                        return f"已保存工作流: {workflow_name}"
                    else:
                        return "保存工作流失败"
                else:
                    return "工作流管理器不支持保存功能"
            
            elif operation == "play_recording":
                workflow_name = params.get("workflow_name")
                speed_factor = params.get("speed_factor", 1.0)
                if not workflow_name:
                    return "请指定要播放的工作流名称"
                
                if hasattr(self.workflow_manager, "execute_workflow"):
                    from workflow_manager import load_workflow
                    workflow_data = load_workflow(workflow_name)
                    if workflow_data and self.workflow_manager.execute_workflow(workflow_data, speed_factor):
                        return f"已开始播放工作流: {workflow_name}"
                    else:
                        return "播放工作流失败"
                elif 'workflow_manager' in globals():
                    from workflow_manager import execute_workflow
                    if execute_workflow(workflow_name, speed_factor):
                        return f"已开始播放工作流: {workflow_name}"
                    else:
                        return "播放工作流失败"
                else:
                    return "工作流管理器不支持播放功能"
            
            else:
                return f"不支持的工作流操作: {operation}"
        except Exception as e:
            logger.error(f"执行工作流操作失败: {str(e)}")
            return f"执行工作流操作时发生错误: {str(e)}"
    
    def _execute_screen_command(self, params: Dict[str, Any]) -> str:
        """执行屏幕内容相关命令"""
        operation = params.get("operation")
        
        try:
            if operation == "screenshot":
                import pyautogui
                import os
                
                # 生成截图文件名
                screenshot_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "screenshots")
                os.makedirs(screenshot_dir, exist_ok=True)
                screenshot_path = os.path.join(screenshot_dir, f"screenshot_{int(time.time())}.png")
                
                # 截图
                pyautogui.screenshot(screenshot_path)
                return f"已完成截图，保存在: {screenshot_path}"
            
            elif operation == "recognize":
                region = params.get("region", "full")
                
                if self.cr_module and hasattr(self.cr_module, "recognize_screen_content"):
                    result = self.cr_module.recognize_screen_content(region=region)
                    return f"屏幕内容识别结果: {result[:200]}{'...' if len(result) > 200 else ''}"
                elif self.ocr_processor:
                    # 使用OCR处理器识别文本
                    import pyautogui
                    
                    # 截图
                    screenshot = pyautogui.screenshot()
                    
                    # 识别文本
                    text = self.ocr_processor.extract_text_from_image(screenshot)
                    return f"屏幕文本识别结果: {text[:200]}{'...' if len(text) > 200 else ''}"
                else:
                    # 尝试直接使用pytesseract作为后备方案
                    try:
                        import pyautogui
                        from PIL import Image
                        import pytesseract
                        
                        # 截图
                        screenshot = pyautogui.screenshot()
                        
                        # 转换为灰度图以提高识别率
                        gray_image = screenshot.convert('L')
                        
                        # 使用pytesseract直接识别
                        text = pytesseract.image_to_string(gray_image, lang='chi_sim+eng')
                        return f"(后备模式)屏幕文本识别结果: {text[:200]}{'...' if len(text) > 200 else ''}"
                    except ImportError:
                        return "OCR模块未初始化，pytesseract也不可用，请检查安装"
                    except Exception as e:
                        return f"使用pytesseract时出错: {str(e)}"
            
            elif operation == "search_text":
                search_text = params.get("search_text")
                if not search_text:
                    return "请指定要搜索的文本"
                
                import pyautogui
                
                # 截图
                screenshot = pyautogui.screenshot()
                
                # 识别文本
                text = ""
                if self.ocr_processor:
                    # 优先使用OCR处理器
                    text = self.ocr_processor.extract_text_from_image(screenshot)
                else:
                    # 尝试直接使用pytesseract作为后备方案
                    try:
                        from PIL import Image
                        import pytesseract
                        
                        # 转换为灰度图以提高识别率
                        gray_image = screenshot.convert('L')
                        
                        # 使用pytesseract直接识别
                        text = pytesseract.image_to_string(gray_image, lang='chi_sim+eng')
                        logger.info("使用pytesseract作为后备OCR方案")
                    except ImportError:
                        return "OCR模块未初始化，pytesseract也不可用，请检查安装"
                    except Exception as e:
                        return f"使用pytesseract时出错: {str(e)}"
                
                # 搜索文本
                if search_text in text:
                    # 查找所有出现位置
                    positions = []
                    start = 0
                    while True:
                        pos = text.find(search_text, start)
                        if pos == -1:
                            break
                        positions.append(pos)
                        start = pos + 1
                    
                    return f"在屏幕上找到了文本 '{search_text}'，共出现 {len(positions)} 次"
                else:
                    return f"在屏幕上未找到文本 '{search_text}'"
            
            else:
                return f"不支持的屏幕操作: {operation}"
        except ImportError as e:
            logger.error(f"缺少必要的库: {str(e)}")
            return "执行屏幕操作需要安装额外的库"
        except Exception as e:
            logger.error(f"执行屏幕操作失败: {str(e)}")
            return f"执行屏幕操作时发生错误: {str(e)}"
    
    def _load_command_mappings(self) -> Dict[str, Dict[str, Any]]:
        """加载命令映射配置"""
        mappings = {
            # 这里可以定义预定义的命令映射
        }
        
        # 尝试从配置文件加载
        try:
            config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "command_mappings.json")
            if os.path.exists(config_path):
                with open(config_path, 'r', encoding='utf-8') as f:
                    mappings.update(json.load(f))
        except Exception as e:
            logger.error(f"加载命令映射配置失败: {str(e)}")
        
        return mappings
    
    def _add_to_history(self, command: str, result: str, intent: Dict[str, Any]) -> None:
        """添加执行历史"""
        with self.lock:
            history_item = {
                "timestamp": time.time(),
                "command": command,
                "result": result,
                "intent": intent
            }
            self.execution_history.append(history_item)
            
            # 限制历史记录大小
            if len(self.execution_history) > 100:
                self.execution_history = self.execution_history[-100:]
    
    def get_execution_history(self, limit: int = 10) -> List[Dict[str, Any]]:
        """获取执行历史
        
        Args:
            limit: 返回的最大记录数
            
        Returns:
            执行历史记录列表
        """
        with self.lock:
            return self.execution_history[-limit:]
    
    def clear_history(self) -> None:
        """清空执行历史"""
        with self.lock:
            self.execution_history.clear()
            logger.info("执行历史已清空")

# 创建全局实例
command_processor = VoiceCommandProcessor()

# 导出常用函数
def process_voice_command(command_text: str) -> str:
    """处理语音命令"""
    return command_processor.process_command(command_text)

def set_processor_components(components=None, **kwargs):
    """设置处理器组件
    
    Args:
        components: 组件字典，包含系统中可用的组件
        **kwargs: 关键字参数形式的组件
    """
    command_processor.set_components(components, **kwargs)

def get_command_history(limit: int = 10) -> List[Dict[str, Any]]:
    """获取命令历史"""
    return command_processor.get_execution_history(limit)

def clear_command_history():
    """清空命令历史"""
    command_processor.clear_history()

# 同时保留原始名称以确保兼容性
voice_command_processor = command_processor

# 初始化函数
def initialize(use_llm: bool = True) -> bool:
    """初始化语音命令处理器
    
    Args:
        use_llm: 是否使用大模型增强
        
    Returns:
        是否初始化成功
    """
    global voice_command_processor
    voice_command_processor = VoiceCommandProcessor(use_llm=use_llm)
    logger.info("语音命令处理器初始化成功")
    return True

# 如果直接运行此模块，执行简单测试
if __name__ == "__main__":
    print("=== 语音命令处理器测试 ===")
    
    if initialize(use_llm=False):
        test_commands = [
            "请告诉我系统内存使用情况",
            "帮我打开记事本",
            "开始录制工作流",
            "截取当前屏幕"
        ]
        
        print("测试命令处理:")
        for cmd in test_commands:
            print(f"\n命令: {cmd}")
            print(f"结果: {process_voice_command(cmd)}")
        
        print("\n处理器已准备就绪，可以开始使用语音命令控制电脑")
    else:
        print("语音命令处理器初始化失败")